package com.efounder.frame.xmlparse;

import android.content.Context;
import android.util.Log;

import com.core.xml.StubObject;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class EFRegistryUtil {
	public EFRegistryUtil() {
	}

	public static void initRegistry(JParamObject po, Context context)
			throws JSONException {
		EFRegistry.clearRegistry();

		// JResponseObject ro = EAI.DAL().IOM(po, "SecurityObject",
		// "initApplication", context);
		JResponseObject ro;
		try {
			ro = EAI.DAL.IOM("SecurityObject", "initApplication", po, null,
					null, null);
			procPackageXML(ro, "PackageClient");
			procPackageXML(ro, "PackagePublic");
			// procPackageJson(ro, "PackageClient");
			// procPackageJson(ro, "PackagePublic");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/***
	 * XXX-初始化注册表
	 * @param xmlFile
     */
	public static void initRegistry(File xmlFile){
		EFRegistry.clearRegistry();
		//首先得到：得到 DOM 解析器的工厂实例
		DocumentBuilderFactory documentBuilderFactory= DocumentBuilderFactory.newInstance();
		try {
			//然后从 DOM 工厂获得 DOM 解析器
			DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
			//把要解析的 XML 文档转化为输入流，以便 DOM 解析器解析它
			InputStream inputStream = new FileInputStream(xmlFile);
			//解析 XML 文档的输入流，得到一个 Document
			Document document = documentBuilder.parse(inputStream);
			Element rootElement = document.getDocumentElement();
			circleReadXML(rootElement);
			//初始化Fragment位置信息
			EFRegistry.initFragmentPositionStore();
			inputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}



	private static void procPackageXML(JResponseObject ro, String key)
			throws ParserConfigurationException, SAXException, IOException {
		ArrayList<String> packList = (ArrayList<String>) ro.getResponseMap().get(key);
		if (packList == null)
			return;
		for (int i = 0; i < packList.size(); i++) {
			StringReader sr = new StringReader(packList.get(i));
			InputSource is = new InputSource(sr);
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(is);
			Element rootElement = doc.getDocumentElement();
			circleReadXML(rootElement);
		}
	}

	private static void circleReadXML(Element element){
		String parentElementName = element.getParentNode().getNodeName();
		Log.d("element","parentElementName:"+parentElementName);
		NodeList nodelist = element.getChildNodes();
		NamedNodeMap attrMap = element.getAttributes();
		if(attrMap != null) {//解析元素对应的属性
			StubObject stubObj = new StubObject();
			for(int i=0;i<attrMap.getLength();i++){
				Node attr=attrMap.item(i);
				String attrName=attr.getNodeName();
				String attrValue=attr.getNodeValue();
				stubObj.setString(attrName, attrValue);
				Log.d("attr","attrName: " + attrName + "     attrValue:" + attrValue );
			}
			stubObj.setString("parentId", parentElementName);
			EFRegistry.regObject(parentElementName, stubObj);
			String id = stubObj.getString(EFXmlConstants.ATTR_ID,"");
			if (!"".equals(id)){//如果有id属性
				EFRegistry.regNode(id,stubObj);
			}
		}
		for(int i=0;i<nodelist.getLength();i++){
			Node childNode=nodelist.item(i);
			short nodeType=childNode.getNodeType();
			if(nodeType == Node.ELEMENT_NODE)
			{
				circleReadXML((Element)childNode);
			}
			else if(nodeType == Node.TEXT_NODE)
			{
				Log.d("TEXT_NODE",childNode.getNodeValue());
			}
			else if(nodeType == Node.COMMENT_NODE)
			{
				Log.d("COMMENT_NODE","<!-- ");
				Comment comment=(Comment)childNode;
				String date=comment.getData();
				Log.d("COMMENT_NODE",date+" -->");
			}
		}
	}

	private static void procPackageJson(JResponseObject ro, String key) throws JSONException {
		ArrayList<String> packList = (ArrayList<String>) ro.getResponseMap().get(key);
		if (packList == null)
			return;

		for (int i = 0; i < packList.size(); i++) {
			String value = packList.get(i);
			JSONObject jsonObject = new JSONObject(value);
			Iterator<String> keyIter = jsonObject.keys();
			String ikey;
			String ivalue;
			while (keyIter.hasNext()) {
				ikey = keyIter.next();
				ivalue = jsonObject.get(ikey).toString();
				StubObject stubObject = new StubObject();
				stubObject.setString(ikey, ivalue);
				EFRegistry.regObject(ikey, stubObject);
			}
		}
	}
}
